package org.dromara.bclt.service.impl;

import org.dromara.bclt.domain.CourseStatus;
import org.dromara.bclt.domain.DeviceInfo;
import org.dromara.bclt.domain.vo.CourseStatusVo;
import org.dromara.bclt.domain.vo.DeviceInfoVo;
import org.dromara.bclt.mapper.CourseStatusMapper;
import org.dromara.bclt.mapper.DeviceInfoMapper;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.dromara.bclt.domain.bo.CourseBo;
import org.dromara.bclt.domain.vo.CourseVo;
import org.dromara.bclt.domain.Course;
import org.dromara.bclt.mapper.CourseMapper;
import org.dromara.bclt.service.ICourseService;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 手环--课程Service业务层处理
 *
 * @author RRyuan
 * @date 2024-10-21
 */
@RequiredArgsConstructor
@Service
public class CourseServiceImpl implements ICourseService {

    private final CourseMapper baseMapper;

    private final DeviceInfoMapper deviceInfoMapper;

    private final CourseStatusMapper courseStatusMapper;


    /**
     * 查询手环--课程
     *
     * @param id 主键
     * @return 手环--课程
     */
    @Override
    public CourseVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    @Override
    public TableDataInfo<CourseVo> getCourseList(CourseBo bo, PageQuery pageQuery) {

        //获取设备注册时间
        DeviceInfoVo deviceInfoVo = deviceInfoMapper.selectVoOne(new LambdaQueryWrapper<DeviceInfo>()
            .select(DeviceInfo::getCreateTime, DeviceInfo::getId)
            .eq(DeviceInfo::getDeviceNumber, bo.getDeviceNumber()));
        //计算当前解锁课程序号
        Long order = (long) (DateUtils.differentDaysByMillisecond(deviceInfoVo.getCreateTime(), DateUtils.getNowDate()) / 7 + 1);
        Long deviceId = deviceInfoVo.getId();
        if (deviceId != null) {
            bo.setDeviceId(deviceId);
        }
        bo.setCourseOrder(order);

        LambdaQueryWrapper<Course> lqw = buildQueryWrapper(bo);
        lqw.orderByDesc(Course::getCourseOrder);
        Page<CourseVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        result.getRecords()
            .forEach(courseVo -> {
                // 处理每个 CourseVo 对象
                CourseStatusVo courseStatusVo = courseStatusMapper.selectVoOne(new LambdaQueryWrapper<CourseStatus>()
                    .select(CourseStatus::getPlayProgress, CourseStatus::getCourseStatus)
                    .eq(CourseStatus::getCourseId, courseVo.getId())
                    .eq(CourseStatus::getDeviceId, bo.getDeviceId()));
                if (courseStatusVo != null) {
                    courseVo.setPlayProgress(Long.valueOf(courseStatusVo.getPlayProgress()));
                    courseVo.setCourseStatus(Long.valueOf(courseStatusVo.getCourseStatus()));
                }else {
                    courseVo.setCourseStatus(0L);
                    courseVo.setPlayProgress(0L);
                }

            });
        return TableDataInfo.build(result);
    }

    /**
     * 分页查询手环--课程列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 手环--课程分页列表
     */
    @Override
    public TableDataInfo<CourseVo> queryPageList(CourseBo bo, PageQuery pageQuery) {
        //getClient=1表示客户端请求
        if(bo.getClient() != null && bo.getClient() == 1){
            //获取设备注册时间
            DeviceInfoVo deviceInfoVo = deviceInfoMapper.selectVoOne(new LambdaQueryWrapper<DeviceInfo>()
                .select(DeviceInfo::getCreateTime)
                .eq(DeviceInfo::getDeviceNumber, bo.getDeviceNumber()));
            //计算当前解锁课程序号
            Long order = (long) (DateUtils.differentDaysByMillisecond(deviceInfoVo.getCreateTime(), DateUtils.getNowDate()) / 7 + 1);
            bo.setCourseOrder(order);
        }
        LambdaQueryWrapper<Course> lqw = buildQueryWrapper(bo);
        lqw.orderByDesc(Course::getCourseOrder);
        Page<CourseVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的手环--课程列表
     *
     * @param bo 查询条件
     * @return 手环--课程列表
     */
    @Override
    public List<CourseVo> queryList(CourseBo bo) {
        LambdaQueryWrapper<Course> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Course> buildQueryWrapper(CourseBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Course> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), Course::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getBcltCourseType()), Course::getBcltCourseType, bo.getBcltCourseType());
        lqw.eq(StringUtils.isNotBlank(bo.getUrl()), Course::getUrl, bo.getUrl());
        lqw.eq(bo.getTotalTime() != null, Course::getTotalTime, bo.getTotalTime());
        lqw.eq(bo.getCreateTime() != null, Course::getCreateTime, bo.getCreateTime());
        lqw.le(bo.getCourseOrder() != null, Course::getCourseOrder, bo.getCourseOrder());

        return lqw;
    }

    /**
     * 新增手环--课程
     *
     * @param bo 手环--课程
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(CourseBo bo) {
        Course add = MapstructUtils.convert(bo, Course.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改手环--课程
     *
     * @param bo 手环--课程
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(CourseBo bo) {
        Course update = MapstructUtils.convert(bo, Course.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Course entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除手环--课程信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public String selectNameById(Long id) {
        return baseMapper.selectVoById(id)!= null ? baseMapper.selectVoById(id).getName() : "";
    }

}
